from apps import jsonrpc, jsonrpc2
from .models import db, GoodsCategory, Goods


@jsonrpc.method("Goods.goods_categoty")
def goods_categoty():
    """商品分类"""
    cat_list = GoodsCategory.query.filter(
        GoodsCategory.is_show == True,
        GoodsCategory.is_deleted == False
    ).order_by(
        db.desc(GoodsCategory.sort),
        db.desc(GoodsCategory.id)
    ).limit(5).all()

    data = []

    for category in cat_list:
        data.append(category.__to_dict__(["id", "name"]))

    return data


@jsonrpc.method("Goods.home_goods")
def home_goods():
    """首页每日"心"品推荐商品"""
    goods_list = Goods.query.filter(
        Goods.is_recommend == True,
        Goods.is_show == True,
        Goods.is_deleted == False
    ).order_by(
        db.desc(Goods.sort),
        db.desc(Goods.id)
    ).limit(10).all()

    data = []
    for goods in goods_list:
        data.append(goods.__to_dict__(["id", "title", "image_url"]))

    return data


@jsonrpc.method("Goods.list_goods(category=Number, page=Number, per_page=Number)")
def list_goods(category=0, page=1, per_page=5):
    """列表页商品列表"""
    data = {}
    try:
        query = Goods.query.filter(
            Goods.is_show == True,
            Goods.is_deleted == False
        ).order_by(
            db.desc(Goods.sort),
            db.desc(Goods.id)
        )

        # 分类ID作为条件查询
        if category > 0:
            query = query.filter(Goods.category_id == category)

        paginate = query.paginate(page, per_page)
        # 当前分页页码
        data["page"] = paginate.page
        # 当前页数据项
        data["items"] = []
        for item in paginate.items:
            goods = item.__to_dict__(["id", "title", "image_url"])
            data["items"].append(goods)
        # 上一页页码
        data["prev_num"] = paginate.prev_num
        # 下一页页码
        data["next_num"] = paginate.next_num
        # 是否有上一页
        data["has_prev"] = paginate.has_prev
        # 是否有下一页
        data["has_next"] = paginate.has_next
        # 总页码
        data["pages"] = paginate.pages
        # 总数据量
        data["total"] = paginate.total

    except:
        data = []

    return data



